/********************************************************************************
*Class:  AddCityControl 
*Method: Search(),Save()
*Useage: Let user choose the city from region and sub-region.
*Notice: We could add email function( send email to every city manage and subordinate ). 
********************************************************************************/

public with sharing class AddCityControl 
{
    
    public String searchFilter{get;set;}
    public List<AddPlaceItemControl> placeList{get;set;}
    public String IdSelect{get;set;}
    public String regionId{get;set;}
    public String msg{get;set;}
    
    
    //get url id
    public String UrlId
    {
        get{        
                return System.currentPageReference().getParameters().get('id');     
           }  
        set;
    }
    
    //option for region
    public List<SelectOption> options 
    {
        get
        {
            if(options == null)
                options = new List<SelectOption>();
            else
                options.clear();
            
            options.add(new SelectOption('','None'));//first Add none value
            string rolename;
            if(userinfo.getuserroleid()!=null)
            roleName=[select id,name from userrole where id=:userinfo.getuserroleid()].name;
            system.assert(rolename!=null,userinfo.getUserroleId());
            string Region=null;
            
            if(roleName=='MMKT:EOC-Senior Regional MMKT Mgr'){
                region='华东区';
            }
            else if(roleName=='MMKT:NOC-Senior Regional MMKT Mgr'){
                region='华北区';
            }
            else if(roleName=='MMKT:SOC-Senior Regional MMKT Mgr'){
                region='华南区';
            }
            else if(roleName=='MMKT:WOC-Senior Regional MMKT Mgr'){
                region='华西区';
            }else{
                msg='对不起，您不是大区经理不能添加城市。';
                
            }
            if(region != null){
            String sql = 'Select p.Id,p.Name From Place__c p where placeType__c=\'Region\' and name=\''+region+'\' '; //      and ownerid=\''+ userinfo.getuserid() +'\'
            for(Place__c pl:Database.query(sql))
            {
                options.add(new SelectOption(pl.Id,pl.Name));
            }
            }
            return options ;
        }
        set;
    }
    
    //option for sub-region
    public List<SelectOption> subRegionOptions
    {    
        get
        {
             if(subRegionOptions == null)
                subRegionOptions = new List<SelectOption>();
            else
                subRegionOptions.clear();
                
            if(IdSelect != NULL)
            {
                String sql = 'select Id,Name from Place__c where Region__c=\''+IdSelect+'\' and placeType__c=\'Sub-region\''; //get region 
            
                for(Place__c pl:Database.query(sql))
                {
                    subRegionOptions.add(new SelectOption(pl.Id,pl.Name));
                }
            }
            return subRegionOptions;
        }       
        set;
    }
      
    //search from region and sub-region
    public PageReference Search()
    {
        if(placeList == null)
            placeList = new List<AddPlaceItemControl>();
        else
            placeList.clear();
                
        if(regionId != NULL)
        {
            String sql='select Id,Name,OwnerId,Changeman__c from Place__c where Subregion__c=\''+regionId+'\' and placeType__c=\'City\'';
            for(Place__c pl:Database.query(sql))
            {               
                placeList.add(new AddPlaceItemControl(pl)); 
            }
        }
        
       return null;
    }
    
    public List<CityNameList__c> rnlList
    {
        get;
        set;
    }
    
    public PageReference Save()
    {
        if(placeList != null)
        {
            if(rnlList == null)
                rnlList = new List<CityNameList__c>();            
        for(AddPlaceItemControl ap:placeList)
        {                       
            if(ap.IsCheck) //checkbox is selected
            {                                      
                RegionNameList__c rnl = [Select Name,Id,HCPEducation__c From RegionNameList__c where Id=:UrlId];                
                CityNameList__c cnl = new CityNameList__c();
                cnl.RegionNameList__c = UrlId;
                if(ap.pItem.Changeman__c == null){
                    msg = '城市所有者没有填写';
                    rnlList.clear();
                    return null;
                }               
                
                list<profile> pid=[select id from profile where name=:'Area/District Sales Manager - Medical' or name=:'Sales Supervisor-Medical'or name=:'Regional Sales Manager - Medical'];
                user u=[select id,profileid,userCity_hidden__c from user where id=:ap.pItem.Changeman__c];
                
                if((u.profileid!=pid[0].id&&u.profileid!=pid[1].id&&u.profileid!=pid[2].id)){
                    msg='城市所有者填写错误';
                    rnllist.clear();
                    return null;
                }
                //================
                
                
                cnl.OwnerId = ap.pItem.Changeman__c;
                cnl.Name = ap.pItem.Name;
                cnl.TargetNo__c = ap.peopleNum;                                                 
                
                RegionNameList__Share rnlShare = new RegionNameList__Share();
                rnlShare.ParentId = UrlId;
                rnlShare.UserOrGroupId = ap.pItem.Changeman__c;
                rnlShare.AccessLevel = 'Read';
                insert rnlShare;
        
                rnlList.add(cnl);
            }
        }

        if(rnlList != null)
        {
            insert rnlList; //insert city list
            
            //go back to region list page
            pageReference pr = new pageReference('/'+ UrlId);     
            pr.setredirect(true);      
            return pr;
        }
        }
        return null;
    }
    
    static testMethod void runtest() {
        Profile p  = [select id from profile where name=: 'Area/District Sales Manager - Medical' limit 1];
        UserRole ur = [Select u.Id From UserRole u where name = 'MMKT:NOC-Senior Regional MMKT Mgr'];
        
           
        User u1 =new User (alias = 'standt',UserRoleId = ur.id, email = 'shlia@isoftstone.com',usercity_hidden__c = '广州', emailencodingkey='UTF-8', lastname = 'Testing', languagelocalekey = 'en_US',UserRegion__c = '华南区',UserSubRegion__c = '华南一区', UserCity__c = '广州',localesidkey='en_US', profileid = p.id, timezonesidkey = 'Asia/Shanghai', username='standarduser@testorg1.com');
        insert u1;
        
       User u2 =new User (alias = 'standt',UserRoleId = ur.id, email = 'shuaicao@isoftstone.com', emailencodingkey='UTF-8', lastname = 'Testing', languagelocalekey = 'en_US',UserRegion__c = '华南区',UserSubRegion__c = '华南一区', UserCity__c = '广州', localesidkey='en_US', profileid = p.id, timezonesidkey = 'Asia/Shanghai', username='ccc@testorg1.com');
        insert u2;


           
        
        String rtid;
        String hcprtid;
        RecordType rt=new recordtype();
        RecordType hcprt=new recordtype();
        hcprt=[select id from recordtype where sobjecttype=:'HCPEducation__c' and name=:'全国医护人员教育活动'];
        rt=[select id from recordtype where sobjectType=:'NationalAttendee__c' and name=:'全国医护人员教育活动']; 
        hcprtid=hcprt.id;
        hcprtid=hcprtid.substring(0,15);
        rtid=rt.id;
        rtid=rtid.substring(0,15);
        
        system.runas(u1){
            Place__c pld = new  Place__c(PlaceType__c = 'Region',name = 'd',ownerid = u1.id);
            insert pld;
    
            Place__c plc = new  Place__c(PlaceType__c = 'Sub-region',name = 'c',Region__c = pld.id);
            insert plc;
            
            Place__c plb = new  Place__c(PlaceType__c = 'Area',name = 'b',Region__c = pld.id, Subregion__c = plc.id);
            insert plb;
                            
            Place__c pla = new  Place__c(PlaceType__c = 'City',name = 'a',  Region__c = pld.id, Subregion__c = plc.id, Area__c = plb.id);
            insert pla;          
        
           hospital__c hp=new hospital__c(name='testhospital',Nickname__c='testnick', approvalstatus__c='审批通过',active__c=true);
           insert hp;
           
           HCP__c hcp1=new hcp__c(Name='testhcp1',Hospital__c=hp.id,Active__c=true,class2__c='决策人(DM)');
           insert hcp1;
           HCP__c hcp2=new hcp__c(Name='testhcp2',Hospital__c=hp.id,Active__c=true,class2__c='决策人(DM)');
           insert hcp2;
          
           HCPEducation__c hcpedu=new HCPEducation__c(name='testsaloon',Venuetype__c = '医院',Hospital__c = hp.Id, OwnerId = u1.Id,date__c=date.today()+30 ,recordtypeid=hcprtid,NOC__c=20,soc__c=20,eoc__c=20,woc__c=20);             //create a saloon type record;
           insert hcpedu;
           
           RegionNameList__c rnl = new RegionNameList__c();
           rnl.name = 'a';
           rnl.hcpeducation__c = hcpedu.Id;
           rnl.OwnerId = u1.Id;
           insert rnl ;
     
              System.currentPageReference().getParameters().put('id',rnl.id);
              AddCityControl acc=new AddCityControl();
              acc.IdSelect = pld.id;
              acc.regionId = plc.id;
              system.assert(acc.options<>null);
              system.assert(acc.subRegionOptions <>null);
              acc.search();            
              
              
              AddPlaceItemControl  apic = new AddPlaceItemControl();
              apic.pItem.name = '广州';
              apic.ischeck=true;
              apic.peopleNum = 20;
              apic.pItem.Changeman__c=u2.id;
              acc.placeList.add(apic);
              
              AddPlaceItemControl  apic1 = new AddPlaceItemControl();
              apic1.pItem.name = '广州';
              apic1.ischeck=false;
              apic1.peopleNum = 20;
              apic1.pItem.Changeman__c= null;
              acc.placeList.add(apic1);
                                            
              acc.save();
        }
        
    }
}